package com.sakiko.audiobook.order.receiver;

import com.rabbitmq.client.Channel;
import com.sakiko.audiobook.common.rabbit.constant.MqConst;
import com.sakiko.audiobook.order.service.OrderInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * projectName: com.sakiko.audiobook.order.receiver
 *
 * @author: sakiko
 * time: 2025/10/11 21:08
 * description: 消费 取消订单消息
 */
@Component
@Slf4j
public class OrderReceiver {

    @Autowired
    private OrderInfoService orderInfoService;

    // 通过配置类配置交换机和队列并完成关系绑定
    @RabbitListener(queues = MqConst.QUEUE_CANCEL_ORDER)
    public void cancelOrder(String orderNo, Message message, Channel channel) {
        log.info("订单服务接收到订单取消消息，订单id:{}", orderNo);
        try {
            if (StringUtils.hasText(orderNo)) {
                orderInfoService.cancelOrder(orderNo);
            }
        } catch (Exception e) {
            log.error("OrderReceiver.cancelOrder:" + e.getMessage());
        }
        try {
            // 手动签收消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
